<template>
  <div class="product-list">
    <!--搜索表单-->
    <div class="common-seach-wrap">
      <el-tabs v-model="activeName" @tab-change="handleClick">
        <el-tab-pane label="出售中" name="sell">
          <template #label>
            <span>
              出售中
              <el-tag>{{ productCount.sell }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="仓库中" name="lower">
          <template #label>
            <span>
              仓库中
              <el-tag>{{ productCount.lower }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="回收站" name="recovery">
          <template #label>
            <span>
              回收站
              <el-tag>{{ productCount.recovery }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="库存紧张" name="stock">
          <template #label>
            <span>
              库存紧张
              <el-tag>{{ productCount.stock }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="待审核" name="audit">
          <template #label>
            <span>
              待审核
              <el-tag>{{ productCount.audit }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="未通过" name="noAudit">
          <template #label>
            <span>
              未通过
              <el-tag>{{ productCount.noAudit }}</el-tag>
            </span>
          </template>
        </el-tab-pane>
      </el-tabs>
      <el-form
        size="small"
        :inline="true"
        :model="searchForm"
        class="demo-form-inline"
      >
        <el-form-item label="商品分类">
          <el-cascader
            size="small"
            style="width: 200px"
            placeholder="请选择"
            v-model="searchForm.categoryId"
            :options="categoryList"
            :props="{
              checkStrictly: true,
              label: 'name',
              value: 'categoryId',
              emitPath: false,
            }"
            clearable
            filterable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            style="width: 200px"
            size="small"
            v-model="searchForm.productName"
            placeholder="请输入商品名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="商品品牌">
          <el-select
            size="small"
            v-model="searchForm.brandId"
            style="width: 200px"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in ssppList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="贸易方式">
          <el-select
            size="small"
            v-model="searchForm.tradeTypeId"
            style="width: 200px"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in tradeTypeList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商户">
          <el-select
            size="small"
            v-model="searchForm.supplierId"
            style="width: 200px"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in supplierList"
              :key="index"
              :label="item.name"
              :value="item.shopSupplierId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品编码">
          <el-input
            style="width: 200px"
            size="small"
            v-model="searchForm.productNo"
            placeholder="请输入商品编码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="是否含税">
          <el-select
            size="small"
            v-model="searchForm.tax"
            style="width: 200px"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in taxList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货仓">
          <el-select
            size="small"
            v-model="searchForm.ware"
            style="width: 200px"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in fhcList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品条形码">
          <el-input
            style="width: 200px"
            size="small"
            v-model="searchForm.productSkuNo"
            placeholder="请输入商品条形码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <div style="display: flex">
            <el-button
              size="small"
              type="primary"
              icon="Search"
              @click="onSubmit"
              >查询</el-button
            >
            <el-button
              size="small"
              type="info"
              @click="onDownload"
              style="margin-left: 10px"
              >下载模板</el-button
            >
            <el-upload
              action="string"
              :show-file-list="false"
              :http-request="uploadFile"
              accept=".xls, .xlsx"
              ref="upload"
            >
              <el-button size="small" type="success" style="margin-left: 10px"
                >导入</el-button
              >
            </el-upload>
            <el-button
              size="small"
              type="warning"
              @click="onExport"
              :loading="exportLoading"
              style="margin-left: 10px"
              >导出</el-button
            >
            <el-button
              size="small"
              type="warning"
              @click="onExportDownload"
              style="margin-left: 10px"
              >导出下载</el-button
            >
            <el-button
              v-if="activeName === 'audit'"
              size="small"
              type="danger"
              @click="onBatchAudit"
              style="margin-left: 10px"
              >批量审核</el-button
            >
            <el-button
              size="small"
              type="danger"
              style="margin-left: 10px"
              @click="batchCommissionRate"
              >批量修改服务费率</el-button
            >
            <el-button
              size="small"
              type="primary"
              style="margin-left: 10px"
              @click="priceTagAll"
              >价签批量打印</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!--添加产品-->
    <!-- <div class="common-level-rail"><el-button size="small" type="primary" icon="el-icon-plus" @click="addClick" v-auth="'/product/product/add'">添加产品</el-button></div> -->
    <div class="common-level-rail" v-if="activeName == 'recovery'">
      <el-button
        size="small"
        type="primary"
        v-auth="'/product/product/add'"
        @click="allDelClick()"
        >一键删除</el-button
      >
    </div>

    <!--内容-->
    <div class="product-content">
      <div class="table-wrap">
        <el-table
          size="small"
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="productName" label="产品" width="400px">
            <template #default="scope">
              <div class="product-info">
                <div class="pic">
                  <img
                    v-img-url="
                      scope.row.imagePath +
                      '?x-oss-process=image/resize,w_120,Q_80'
                    "
                    alt
                  />
                </div>
                <div class="info">
                  <div class="name">{{ scope.row.productName }}</div>
                  <div class="price">￥{{ scope.row.productPrice }}</div>
                  <div class="price" v-if="activeName == 'noAudit'">
                    未通过原因：{{ scope.row.auditRemark }}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="categoryName" label="分类"></el-table-column>
          <el-table-column prop="supplierName" label="商户"></el-table-column>
          <el-table-column prop="commissionRate" label="服务费率">
            <template #default="scope">
              <span>{{ scope.row.commissionRate }}%</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="salesActual"
            label="实际销量"
          ></el-table-column>
          <el-table-column prop="productStock" label="库存" width="200">
            <template #default="scope">
              <div style="white-space: pre-wrap">
                {{ handleSku(scope.row) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="viewTimes" label="点击数"></el-table-column>
          <el-table-column
            prop="tradeTypeName"
            label="贸易方式"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            label="发布时间"
            width="130"
          ></el-table-column>
          <el-table-column prop="productSort" label="排序"></el-table-column>
          <el-table-column fixed="right" label="操作" width="80">
            <template #default="scope">
              <div class="table-btn-column">
                <el-button
                  @click="priceLook(scope.row)"
                  link
                  type="primary"
                  size="small"
                  v-auth="'/product/product/edit'"
                  >价签预览</el-button
                >
                <el-button
                  v-if="scope.row.auditStatus == 10"
                  @click="editClick(scope.row)"
                  link
                  type="primary"
                  size="small"
                  v-auth="'/product/product/edit'"
                  >编辑商品</el-button
                >
                <el-button
                  v-if="scope.row.auditStatus == 0"
                  @click="editClick(scope.row)"
                  link
                  type="primary"
                  size="small"
                  v-auth="'/product/product/edit'"
                  >审核商品</el-button
                >
                <div>
                  <el-button
                    v-if="activeName == 'sell'"
                    @click="changeStatus(scope.row, 20)"
                    link
                    type="primary"
                    size="small"
                    v-auth="'/product/product/edit'"
                    >立即下架</el-button
                  >
                </div>
                <div>
                  <el-button
                    v-if="activeName == 'lower'"
                    @click="changeStatus(scope.row, 10)"
                    link
                    type="primary"
                    size="small"
                    v-auth="'/product/product/edit'"
                    >立即上架</el-button
                  >
                </div>
                <div>
                  <el-button
                    @click="delClick(scope.row)"
                    link
                    type="primary"
                    size="small"
                    v-auth="'/product/product/delete'"
                    >删除商品</el-button
                  >
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!--分页-->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="curPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalDataNumber"
      ></el-pagination>
    </div>
    <el-dialog
      title="批量审核"
      class="product-batch-audit-dialog"
      append-to-body
      v-model="dialogVisible"
      width="500px"
    >
      <el-form size="small" label-width="90px" :model="auditParams">
        <el-form-item
          label="审核状态："
          :rules="[{ required: true, message: '选择审核状态' }]"
          prop="state"
        >
          <el-radio-group v-model="auditParams.state">
            <el-radio :label="10">通过</el-radio>
            <el-radio :label="20">未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注：">
          <el-input
            type="textarea"
            :rows="4"
            v-model="auditParams.remark"
            placeholder="请输入拒绝原因"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onBatchAuditConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="批量修改服务费率"
      class="product-batch-audit-dialog"
      append-to-body
      v-model="commissionRateDialogVisible"
      width="500px"
    >
      <el-form
        ref="dialogBatchCommissionRate"
        size="small"
        label-width="90px"
        :model="commissionRateParams"
      >
        <el-form-item
          label="服务费率："
          prop="commissionRate"
          :rules="[{ required: true, message: '请输入服务费率' }]"
        >
          <el-input-number
            v-model="commissionRateParams.commissionRate"
            :precision="2"
            :step="0.01"
            step-strictly
            :min="0.01"
            :max="300"
            :controls="false"
          />%
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="commissionRateDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="onBatchCommissionRateConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="价签预览"
      class="product-batch-audit-dialog"
      append-to-body
      v-model="priceLookPup"
      width="360px"
    >
      <ddd :lookSkuList="lookSkuList" @close="priceLookPup = false"></ddd>

      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="priceLookPup = false">取 消</el-button>
        <el-button type="primary" @click="lookPoint">打印</el-button>
      </span>-->
    </el-dialog>

    <el-dialog
      title="导出下载"
      append-to-body
      v-model="exportDialogVisible"
      width="900px"
    >
      <el-table :data="exportList" border style="width: 100%">
        <el-table-column prop="id" label="订单导出id" width="100px">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"> </el-table-column>
        <el-table-column prop="status" label="状态"> </el-table-column>
        <el-table-column prop="errorMsg" label="失败原因"> </el-table-column>
        <el-table-column label="操作" width="100px">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '导出成功！'"
              type="text"
              size="small"
              @click="exportDownload(scope.row)"
              >下载</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import ddd from "@/views/product/product/print.vue";
import qs from "qs";
import PorductApi from "@/api/product.js";
import { useUserStore } from "@/store";
import printJS from "print-js";
const { token } = useUserStore();
export default {
  components: { ddd },
  data() {
    return {
      lookSkuList: [],
      priceLookPup: false,
      token,
      /*切换菜单*/
      activeName: "sell",
      /*切换选中值*/
      activeIndex: "0",
      /*是否正在加载*/
      loading: true,
      /*一页多少条*/
      pageSize: 15,
      /*一共多少条数据*/
      totalDataNumber: 0,
      /*当前是第几页*/
      curPage: 1,
      /*搜索参数*/
      searchForm: {
        productName: "",
        categoryId: "",
        brandId: "",
        tradeTypeId: "",
        productNo: "",
        productSkuNo: "",
        ware: "",
        tax: "",
        supplierId: "",
      },
      /*列表数据*/
      tableData: [],
      /*全部分类*/
      categoryList: [],
      productCount: {},
      multipleSelection: [],
      dialogVisible: false,
      auditParams: {
        state: 10,
        remark: "",
      },
      commissionRateParams: {
        commissionRate: undefined,
      },
      commissionRateDialogVisible: false,
      exportLoading: false,
      ssppList: [],
      tradeTypeList: [],
      supplierList: [],
      taxList: [
        {
          name: "是",
          id: 1,
        },
        {
          name: "否",
          id: 0,
        },
      ],
      fhcList: [
        {
          id: 1,
          name: "门店",
        },
        {
          id: 2,
          name: "公共仓",
        },
        {
          id: 3,
          name: "唯品会仓",
        },
        {
          id: 4,
          name: "行云仓",
        },
      ],
      exportDialogVisible: false,
      exportList: [],
    };
  },
  created() {
    const type = this.$route.query.type || "sell";
    this.getBrandList();
    this.tradeTypeListInit();
    /*获取列表*/
    this.getData(type);
  },
  methods: {
    tradeTypeListInit() {
      PorductApi.tradeTypeIndex().then((res) => {
        this.tradeTypeList = res.data.records;
      });
    },
    getBrandList() {
      PorductApi.brandIndex({
        pageIndex: 1,
        pageSize: 999999,
      }).then((res) => {
        this.ssppList = res.data.records;
      });
    },
    onDownload() {
      window.open(
        `https://baoshuiqu2024.oss-cn-beijing.aliyuncs.com/%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx?t=${new Date().getTime()}`,
        "download"
      );
    },
    uploadFile(param) {
      const loading = ElLoading.service({
        lock: true,
        text: "正在上传,请等待",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const formData = new FormData();
      formData.append("file", param.file);
      PorductApi.batchImport(formData)
        .then((response) => {
          loading.close();
          this.onSubmit();
          ElMessage({
            message: "导入成功",
            type: "success",
          });
        })
        .catch((response) => {
          loading.close();
          ElMessage({
            message: "本次处理失败",
            type: "warning",
          });
          param.onError();
        });
    },
    handleSku(row) {
      if (!row.sku) return "";
      return row.sku
        .map((v) => `${v.productAttr}--${v.productPrice}--${v.stockNum}`)
        .join("\n");
    },
    onBatchAuditConfirm() {
      const self = this;
      PorductApi.batchAudit({
        productIds: self.multipleSelection.map((v) => v.productId).join(","),
        ...self.auditParams,
      })
        .then((data) => {
          ElMessage({
            message: "操作成功",
            type: "success",
          });
          self.dialogVisible = false;
          self.getData();
        })
        .catch((error) => {});
    },
    batchCommissionRate() {
      if (!this.multipleSelection.length) {
        ElMessage({
          message: "请选择要修改的商品",
          type: "warning",
        });
        return;
      }
      this.commissionRateParams.commissionRate = undefined;
      this.commissionRateDialogVisible = true;
    },
    onBatchCommissionRateConfirm() {
      const self = this;
      self.$refs.dialogBatchCommissionRate.validate((valid) => {
        if (valid) {
          PorductApi.batchCommissionRate({
            productIds: self.multipleSelection
              .map((v) => v.productId)
              .join(","),
            ...self.commissionRateParams,
          })
            .then((data) => {
              ElMessage({
                message: "操作成功",
                type: "success",
              });
              self.commissionRateDialogVisible = false;
              self.getData();
            })
            .catch((error) => {});
        }
      });
    },
    onBatchAudit() {
      if (!this.multipleSelection.length) {
        ElMessage({
          message: "请选择要审核的商品",
          type: "warning",
        });
        return;
      }
      this.dialogVisible = true;
    },
    onExport() {
      this.exportLoading = true;
      let Params = this.searchForm;
      Params.pageIndex = 1;
      Params.pageSize = 999999;
      Params.type = this.activeName;
      this.exportLoading = true;
      PorductApi.batchExport(Params, true).then((res) => {
        ElMessage.success("导出中，请耐心等待");
        this.exportLoading = false;
      });
    },

    onExportDownload() {
      this.exportDialogVisible = true;
      PorductApi.exportRecord().then((res) => {
        this.exportList = res.data.list;
      });
    },

    exportDownload(row) {
      window.open(row.url);
    },

    handleSelectionChange(e) {
      this.multipleSelection = e;
    },
    /*选择第几页*/
    handleCurrentChange(val) {
      let self = this;
      self.loading = true;
      self.curPage = val;
      self.getData();
    },

    /*每页多少条*/
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },

    /*切换菜单*/
    handleClick(tab, event) {
      let self = this;
      self.curPage = 1;
      self.multipleSelection = [];
      self.getData();
    },

    /*获取列表*/
    getData(type) {
      let self = this;
      let Params = self.searchForm;
      Params.pageIndex = self.curPage;
      Params.pageSize = self.pageSize;
      Params.type = type || self.activeName;
      self.loading = true;
      PorductApi.productList(Params, true)
        .then((res) => {
          self.loading = false;
          self.tableData = res.data.productList.records;
          self.categoryList = res.data.categoryList;
          self.totalDataNumber = res.data.productList.total;
          self.productCount = res.data.productCount;
          self.supplierList = res.data.supplierList;
          if (type) self.activeName = type;
        })
        .catch((error) => {
          self.loading = false;
        });
    },

    /*搜索查询*/
    onSubmit() {
      this.curPage = 1;
      this.getData();
    },

    /*打开添加*/
    addClick() {
      window.open("/shop/#/product/product/add");
    },
    // 批量标签
    priceTagAll() {
      this.lookSkuList = [];
      // console.log(this.multipleSelection, "this.multipleSelection");
      this.lookSkuList = this.multipleSelection;
      if (this.lookSkuList && this.lookSkuList.length == 0) {
        ElMessage({
          message: "请选择需要打印的数据",
          type: "warning",
        });
        return;
      }
      this.priceLookPup = true;
      // console.log("我爱你");
    },
    // 预览

    priceLook(row) {
      this.lookSkuList = [];
      this.priceLookPup = true;
      this.lookSkuList.push(row);
      console.log(row, "我是预览的");
    },
    lookPoint() {
      printJS({
        // 要打印的html的节点id
        printable: "woaini",
        // 打印类型 html
        type: "html",
        // 继承样式
        scanStyles: true,
        // 默认800，设置1000是因为我窗口宽度是1000，而导致页面靠近左边，设置1000就正常居中了。

        targetstyles: ["*"],

        maxwidth: 1000,
        css: "@/views/product/product/com/print.css",
        // scanstyles: false
      });
    },
    /*打开编辑*/
    editClick(row) {
      window.open(
        `/shop/#/product/product/edit?productId=${row.productId}&scene=edit`
      );
    },

    linkClick: function (val) {
      let self = this;
      let copyText = "pages/product/detail/detail?productId=" + val;
      self.$copyText(copyText).then(
        function (e) {
          ElMessage({
            showClose: true,
            message: "复制成功",
            type: "success",
          });
        },
        function (e) {
          ElMessage({
            showClose: true,
            message: "复制失败",
            type: "error",
          });
        }
      );
    },
    /*打开复制*/
    copyClick(row) {
      window.open(
        `/shop/#/product/product/edit?productId=${row.productId}&scene=copy`
      );
    },
    /*删除*/
    delClick: function (row) {
      let self = this;
      let msg = "";
      if (row.productStatus == 30) {
        msg = "删除后不可恢复，确认删除该记录吗?";
      } else {
        msg = "删除后将移动到回收站，确定删除该记录吗?";
      }
      ElMessageBox.confirm(msg, "提示", {
        type: "warning",
      }).then(() => {
        PorductApi.delProduct({
          productId: row.productId,
        }).then((data) => {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          self.getData();
        });
      });
    },
    /*多选删除*/
    allDelClick() {
      let ids = [];
      let self = this;
      self.multipleSelection.forEach((v) => {
        ids.push(v.productId);
      });
      ids = ids.join(",");
      ElMessageBox.confirm("删除后不可恢复，确认删除该记录吗?", "提示", {
        type: "warning",
      }).then(() => {
        PorductApi.allDelProduct({
          productIds: ids,
        }).then((data) => {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          self.getData();
        });
      });
    },
    /*修改状态*/
    changeStatus(item, value) {
      let self = this;
      let msg = "";
      if (value == 10) {
        msg = "确认要上架该商品吗?";
      } else {
        msg = "确认要下架该商品吗?";
        if (self.activeName == "recovery") {
          msg = "确认要移动该商品到仓库吗?";
        }
      }
      ElMessageBox.confirm(msg, "提示", {
        type: "warning",
      }).then(() => {
        PorductApi.changeStatus({
          productId: item.productId,
          state: value,
        }).then((data) => {
          ElMessage({
            message: "操作成功",
            type: "success",
          });
          self.getData();
        });
      });
    },
  },
};
</script>

<style lang="scss">
@import url("@/views/product/product/com/print.css");

// .bo2 {
//   // border: 1px solid red;
//   text-align: center;
// }
// .bo3 {
//   border: 1px solid red;
//   text-align: center;
//   padding: 10px;
// }
// .bo1 {
//   border: 1px solid red;
//   padding: 10px;
//   // text-align: center;
// }
.product-batch-audit-dialog {
  .el-dialog__body {
    padding: 0 !important;
  }
}
</style>
